#include <arpa/inet.h>
#include <errno.h>
#include <netinet/in.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>

#include "testcommon.h"
#include "zeppreactor.h"

GLOBAL_INIT_TEST

// 测试用例1: 基本功能测试
void test_basic_functionality() {
  printf("=== 测试用例1: 基本功能测试 ===\n");

  struct zeppreactor reactor;
  int result = zeppreactor_init(&reactor);
  EXPECT_EQ(1, result);

  int sockfd = init_socket(DEFAULT_PORT);
  EXPECT_GT(sockfd, 0);

  result = zeppreactor_addlistener(&reactor, sockfd, accept_cb);
  EXPECT_EQ(0, result);

  close(sockfd);
  zeppreactor_destory(&reactor);

  printf("基本功能测试通过\n\n");
}

// 客户端线程函数
void *client_thread(void *arg) {
  int port = *(int *)arg;
  // 等待服务器启动

  int clientfd = socket(AF_INET, SOCK_STREAM, 0);
  if (clientfd < 0) {
    printf("创建客户端socket失败\n");
    return NULL;
  }

  struct sockaddr_in serveraddr;
  memset(&serveraddr, 0, sizeof(serveraddr));
  serveraddr.sin_family = AF_INET;
  serveraddr.sin_addr.s_addr = inet_addr("127.0.0.1");
  serveraddr.sin_port = htons(port);

  // 连接服务器
  if (connect(clientfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) <
      0) {
    printf("连接服务器失败: %s\n", strerror(errno));
    close(clientfd);
    return NULL;
  }

  // 发送测试数据
  const char *test_data = "Hello Reactor!";
  if (send(clientfd, test_data, strlen(test_data), 0) < 0) {
    printf("发送数据失败: %s\n", strerror(errno));
    close(clientfd);
    return NULL;
  }

  // 接收回显数据
  char buffer[BUFFER_LENGTH];
  ssize_t len = recv(clientfd, buffer, BUFFER_LENGTH - 1, 0);
  if (len > 0) {
    buffer[len] = '\0';
    printf("收到回显数据: %s\n", buffer);
    EXPECT_EQ_STR(test_data, buffer);
  } else {
    printf("接收数据失败: %s\n", strerror(errno));
  }

  close(clientfd);
  return NULL;
}

// 测试用例2: 连接和数据传输测试
TEST_SUITE(connection_and_data_transfer) {
  printf("=== 测试用例2: 连接和数据传输测试 ===\n");
  struct zeppreactor reactor;
  int port = DEFAULT_PORT;

  pthread_t client_tid;
  pthread_t server_tid;
  pthread_create(&client_tid, NULL, client_thread, &port);
  pthread_join(client_tid, NULL);

  printf("连接和数据传输测试完成\n\n");
}

// 测试用例3: 多连接测试
TEST_SUITE(multiple_connections) {
  printf("=== 测试用例3: 多连接测试 ===\n");

  int port = DEFAULT_PORT;

  // 创建多个客户端线程
  pthread_t client_tids[25];
  for (int i = 0; i < 25; i++) {
    pthread_create(&client_tids[i], NULL, client_thread, &port);
  }

  // 等待所有客户端线程完成
  for (int i = 0; i < 25; i++) {
    pthread_join(client_tids[i], NULL);
  }

  printf("多连接测试完成\n\n");
}

int main() {
  printf("开始测试zeppreactor功能\n\n");

  // test_basic_functionality();
  RUN_TEST_SUITE(connection_and_data_transfer);
  RUN_TEST_SUITE(multiple_connections);

  OUTPUT_TEST_RESULT();
  RETURN_TEST_RESULT();
}